package com.wlps.aspect;

import com.alibaba.fastjson.JSONObject;
import com.wlps.entity.WebLog;
import com.wlps.config.RedisConfig;
import com.wlps.mapper.WebLogMapper;
import com.wlps.result.ResultVo;
import com.wlps.utils.JwtUtils;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 *
 * 日志切面及redis关闭连接
 * @param
 * @return
 */

@Aspect
@Component
@Order(2)
public class WebLogAspect {
    @Autowired
    WebLogMapper webLogMapper;
    @Autowired
    Jedis jedis;
    @Autowired
    JwtUtils jwtUtils;
    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);
    @Pointcut("execution(public * com.wlps.controller.*.*(..))")
    public void webLog(){}
    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret){
    }
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime=System.currentTimeMillis();
        //获取当前请求对象
        Object proceed = null;
        ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes!=null) {
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("token");

            WebLog webLog = new WebLog();
            proceed = joinPoint.proceed();
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature=(MethodSignature)signature;
            Method method = methodSignature.getMethod();
            if(method.isAnnotationPresent(ApiOperation.class)){
                ApiOperation annotation = method.getAnnotation(ApiOperation.class);
                webLog.setDescription(annotation.value());
            }
            long endTime = System.currentTimeMillis();
            String urlString = request.getRequestURI().toString();
            webLog.setBasePath(urlString);
            webLog.setUsername(jwtUtils.getUsernameFromToken(token));
            webLog.setIp(request.getRemoteAddr());
            webLog.setMethod(request.getMethod());
            webLog.setParameter(Arrays.toString(joinPoint.getArgs()));
             webLog.setResult(proceed);
            webLog.setSpendTime((int)(endTime-startTime));
            webLog.setStartTime(startTime);
            webLog.setUri(request.getRequestURI());
            webLog.setUrl(request.getRequestURL().toString());
            webLogMapper.insert(webLog);
            LOGGER.info("操作记录写入数据库");
            Map<String,Object>logMap=new HashMap<>();
            logMap.put("url",webLog.getUrl());
            logMap.put("method",webLog.getMethod());
            logMap.put("parameter",webLog.getParameter());
            logMap.put("spendTime",webLog.getSpendTime());
            logMap.put("description",webLog.getDescription());
            LOGGER.info("调试数据=========>"+JSONObject.toJSONString(webLog.toString()));

            LOGGER.info(JSONObject.toJSONString(logMap));
            RedisConfig.returnJedis(jedis);
        }
        return proceed;
    }
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);

            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        LOGGER.info("传入数据信息=====>"+argList);
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}
